import { ModuleType, StoreModuleData } from '../modules/TypeConstraints';
import { StoreState } from '../store/module';
import { IModuleData as IContainerModuleData } from './../modules/Container/moduleClass';

// 根据zIndex 对所有的components排序
export function sortModuleDataListByZIndex(
  moduleDataListMap: StoreState['moduleDataListMap'],
) {
  const moduleDataIds = Object.keys(moduleDataListMap);
  // 从小到大排序
  moduleDataIds.sort(
    (firstId, secondId) =>
      moduleDataListMap[firstId].props.zIndex -
      moduleDataListMap[secondId].props.zIndex,
  );
  return moduleDataIds;
}

// 判断moduleData是否为容器类型
export function isContainer(
  data: StoreModuleData,
): data is IContainerModuleData {
  return data.type === ModuleType.Container;
}

// 通过id获取查找data的路径
export function getModuleDataPaths(
  id: StoreModuleData['id'],
  nodeList: StoreModuleData[],
) {
  const paths: StoreModuleData[] = [];
  function eachNode(nodeList?: StoreModuleData[]) {
    if (!nodeList?.length) return false;

    for (const node of nodeList) {
      paths.push(node);
      if (node.id === id) {
        return true;
      }
      if (isContainer(node) && eachNode(node.props?.children)) return true;
      paths.pop();
    }

    return false;
  }

  eachNode(nodeList);
  return paths;
}

// 通过id获取moduleData
export function getModuleDataById(
  id: StoreModuleData['id'],
  nodeList: StoreModuleData[],
) {
  const paths = getModuleDataPaths(id, nodeList);
  const length = paths.length;
  if (!length) return null;
  const node = paths.pop() as StoreModuleData;
  const parent = paths.pop();

  return {
    node,
    parent: parent || null,
    paths,
  };
}
